import React, { useState, useEffect } from 'react';
import { Button, Input, Space, Popconfirm, message, Tag, Select, Modal, Form } from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined, 
  DeleteOutlined, 
  EditOutlined,
  FileTextOutlined,
  EyeOutlined,
  BarChartOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { FilterCard, TableCard } from '@/components/common';
import { PaperListItem, PaperStatus, QuestionBank } from '@/types/question';
import { questionService } from '@/services/questionService';

const { Option } = Select;

const PaperList: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [papers, setPapers] = useState<PaperListItem[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState<PaperStatus | undefined>();
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [createLoading, setCreateLoading] = useState(false);
  const [questionBanks, setQuestionBanks] = useState<QuestionBank[]>([]);
  const [form] = Form.useForm();

  // 加载试卷列表
  const fetchPapers = async (page = 1) => {
    setLoading(true);
    try {
      const response = await questionService.getPapers({
        page,
        limit: pagination.pageSize,
        keyword: searchKeyword || undefined,
        status: statusFilter,
      });
      const data = response.data.data;
      setPapers(data.results);
      setPagination({
        ...pagination,
        current: page,
        total: data.count,
      });
    } catch (error) {
      message.error('获取试卷列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPapers(1);
  }, [statusFilter]);

  useEffect(() => {
    if (createModalVisible) {
      loadQuestionBanks();
    }
  }, [createModalVisible]);

  // 加载题库列表
  const loadQuestionBanks = async () => {
    try {
      const response = await questionService.getQuestionBanks({ page: 1, limit: 100 });
      const data = response.data.data;
      setQuestionBanks(data.results);
    } catch (error) {
      message.error('加载题库列表失败');
    }
  };

  // 搜索
  const handleSearch = () => {
    fetchPapers(1);
  };

  // 打开新建试卷弹窗
  const handleOpenCreateModal = () => {
    setCreateModalVisible(true);
    form.resetFields();
  };

  // 创建试卷
  const handleCreatePaper = async (values: any) => {
    setCreateLoading(true);
    try {
      const response = await questionService.createPaper({
        title: values.title,
        description: '',
        status: PaperStatus.DRAFT,
        is_public: false,
        duration: 120,
        total_score: 0,
        passing_score: 60,
        show_score_after_submit: true,
        show_answer_after_submit: false,
        show_analysis_after_submit: false,
        random_question_order: false,
        random_choice_order: false,
        allow_multiple_submit: false,
        max_submit_count: 1,
      });
      
      message.success('试卷创建成功');
      setCreateModalVisible(false);
      
      // 跳转到编辑页面，并传递默认题库ID
      const bankParam = values.question_bank ? `?defaultBank=${values.question_bank}` : '';
      navigate(`/admin/question/paper/edit/${response.data.data.id}${bankParam}`);
    } catch (error: any) {
      message.error(error.response?.data?.message || '创建试卷失败');
    } finally {
      setCreateLoading(false);
    }
  };

  // 删除试卷
  const handleDelete = async (id: number) => {
    try {
      await questionService.deletePaper(id);
      message.success('删除成功');
      fetchPapers(pagination.current);
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 状态映射
  const statusMap: Record<string, { color: string; text: string }> = {
    draft: { color: 'default', text: '草稿' },
    published: { color: 'green', text: '已发布' },
    ended: { color: 'red', text: '已结束' },
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '试卷标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: PaperListItem) => (
        <a onClick={() => navigate(`/admin/question/paper/edit/${record.id}`)}>
          {text}
        </a>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = statusMap[status] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '题目数',
      dataIndex: 'question_count',
      key: 'question_count',
      width: 100,
      render: (count: number) => <Tag color="blue">{count} 道</Tag>,
    },
    {
      title: '总分',
      dataIndex: 'total_score',
      key: 'total_score',
      width: 80,
    },
    {
      title: '时长',
      dataIndex: 'duration',
      key: 'duration',
      width: 100,
      render: (duration: number) => `${duration}分钟`,
    },
    {
      title: '提交人数',
      dataIndex: 'submit_count',
      key: 'submit_count',
      width: 100,
    },
    {
      title: '可见性',
      dataIndex: 'is_public',
      key: 'is_public',
      width: 80,
      render: (isPublic: boolean) => (
        <Tag color={isPublic ? 'green' : 'default'}>
          {isPublic ? '公开' : '私有'}
        </Tag>
      ),
    },
    {
      title: '创建者',
      dataIndex: 'created_by_name',
      key: 'created_by_name',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 180,
      render: (time: string) => new Date(time).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      fixed: 'right' as const,
      render: (_: any, record: PaperListItem) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => navigate(`/admin/question/paper/edit/${record.id}`)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => window.open(`/client/paper/exam/${record.id}`, '_blank')}
          >
            预览
          </Button>
          <Popconfirm
            title="确定要删除此试卷吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <FilterCard
        pageTitle="试卷管理"
        titleIcon={<FileTextOutlined />}
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleOpenCreateModal}
          >
            新建试卷
          </Button>
        }
      >
        <Space size="middle" wrap>
          <Input
            placeholder="搜索试卷标题"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onPressEnter={handleSearch}
            prefix={<SearchOutlined />}
            style={{ width: 250 }}
          />

          <Select
            placeholder="状态筛选"
            style={{ width: 150 }}
            allowClear
            value={statusFilter}
            onChange={setStatusFilter}
          >
            <Option value="draft">草稿</Option>
            <Option value="published">已发布</Option>
            <Option value="ended">已结束</Option>
          </Select>

          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
        </Space>
      </FilterCard>

      <TableCard
        tableProps={{
          columns,
          dataSource: papers,
          rowKey: 'id',
          loading,
          scroll: { x: 1400 },
          pagination: {
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: (page) => {
              setPagination({ ...pagination, current: page });
              fetchPapers(page);
            },
          },
        }}
      />

      {/* 新建试卷弹窗 */}
      <Modal
        title="新建试卷"
        open={createModalVisible}
        onOk={() => form.submit()}
        onCancel={() => setCreateModalVisible(false)}
        confirmLoading={createLoading}
        okText="创建"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreatePaper}
        >
          <Form.Item
            name="title"
            label="试卷标题"
            rules={[{ required: true, message: '请输入试卷标题' }]}
          >
            <Input placeholder="请输入试卷标题" />
          </Form.Item>

          <Form.Item
            name="question_bank"
            label="默认题库"
            extra="新建题目时将自动关联到此题库（可选）"
          >
            <Select placeholder="选择题库" allowClear>
              {questionBanks.map(bank => (
                <Option key={bank.id} value={bank.id}>
                  {bank.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PaperList;

